import 'whatwg-fetch'

function getNewUrl(url, obj) {
    let arr = [];
    Object.keys(obj).forEach(v => {
        arr.push(`${v}=${obj[v]}`)
    })
    if (url.search(/\?/) === -1) {
        url += '?' + arr.join('&')
    } else {
        url += '&' + arr.join('&')
    }
    return url;
}

 const HTTPUtil = params => {
    //  post 请求
    let url = params.url || '',
        // get 请求，默认
        type = params.type || 'GET',
        data = params.data || {},
        headers = params.headers || {},
        successCallback = params.success
        
     if (type == 'POST' || type == 'post') {
         console.log(data)
        //  headers = headers || {'Content-Type': 'application/json; charset=utf-8'}
        return fetch(url, {
            method: 'POST',
            headers: {'Content-Type': 'application/json; charset=utf-8'},
            body: JSON.stringify(data)
        }).then(res => {
            return res.json()
        }).then(data => {
            successCallback(data)
        })
     }else if(type == "GET" || type == 'get'){
        // get 请求，默认
        let newUrl = getNewUrl(url, data)
       return fetch(newUrl).then(res => {
            return res.json()
        }).then(data => {
            successCallback(data)
        })
     }
 }
 window.$fetch = HTTPUtil

  // fetch('/api/addArticle', {
        //     method: 'POST',
        //     headers:{
        //         'Content-Type': 'application/json; charset=utf-8'
        //     },
        //     body: JSON.stringify( {
        //         type: 1,
        //         articleName,
        //         markdown:content,
        //         time,
        //         introduction,
        //     })
        // }).then(res => {

        // })

